﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Http
{
    public static class SessionExtensions
    {
        public static void setValue<T>(this ISession session, string key, T val) where T : class, new()
        {
            session.SetString(key, JsonConvert.SerializeObject(val));
        }

        /// <summary>
        /// 如果key不存在, new 一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <returns>每次获取的都是一个新的对象, 相当于镜像</returns>
        public static T getValue<T>(this ISession session, string key) where T : class, new()
        {
            if (session.Keys.Contains(key))
            {
                var val = session.GetString(key);
                return JsonConvert.DeserializeObject<T>(val);
            }
            else
            {
                return new T();
            }
        }
    }
}
